package cn.ug.pay.service.impl;

import cn.ug.bean.LoginBean;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.config.RedisGlobalLock;
import cn.ug.core.ensure.Ensure;
import cn.ug.core.login.LoginHelper;
import cn.ug.feign.MemberUserService;
import cn.ug.feign.PriceService;
import cn.ug.pay.bean.MemberGoldBean;
import cn.ug.pay.bean.request.ApplyExtractGoldBean;
import cn.ug.pay.bean.request.ExtractGoldParamBean;
import cn.ug.pay.bean.response.BankCardManageBean;
import cn.ug.pay.bean.response.ExtractGoldBean;
import cn.ug.pay.bean.status.CommonConstants;
import cn.ug.pay.bean.status.PayDistributePrefix;
import cn.ug.pay.bean.type.BillGoldTradeType;
import cn.ug.pay.mapper.ExtractGoldMapper;
import cn.ug.pay.mapper.entity.ExtractGold;
import cn.ug.pay.service.ExtractGoldService;
import cn.ug.pay.service.MemberGoldService;
import cn.ug.util.Common;
import cn.ug.util.IdcardValidator;
import cn.ug.util.SerialNumberWorker;
import cn.ug.util.UF;
import com.github.pagehelper.PageHelper;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ExtractGoldServiceImpl implements ExtractGoldService {

    @Resource
    private MemberUserService memberUserService;

    @Resource
    private MemberGoldService memberGoldService;

    @Resource
    private PriceService priceService;

    @Resource
    private ExtractGoldMapper extractGoldMapper;

    @Resource
    private DozerBeanMapper dozerBeanMapper;

    @Resource
    private RedisGlobalLock redisGlobalLock;

    private static Logger logger = LoggerFactory.getLogger(ExtractGoldServiceImpl.class);


    @Override
    public DataTable<ExtractGoldBean> findList(ExtractGoldParamBean extractGoldParamBean) {
        com.github.pagehelper.Page<BankCardManageBean> pages = PageHelper.startPage(extractGoldParamBean.getPageNum(),extractGoldParamBean.getPageSize());
        List<ExtractGoldBean> dataList = extractGoldMapper.findList(extractGoldParamBean);
        if(dataList != null){
            for(ExtractGoldBean entity:dataList){
                String idCard = entity.getIdCard();
                entity.setIdCard(idCard.substring(0,idCard.length() -8) + "********");
            }
        }
        return new DataTable<>(extractGoldParamBean.getPageNum(), extractGoldParamBean.getPageSize(), pages.getTotal(), dataList);
    }

    @Override
    public ExtractGoldBean findById(String id) {
        ExtractGold extractGold = extractGoldMapper.findById(id);
        if(extractGold != null){
            ExtractGoldBean entity = dozerBeanMapper.map(extractGold, ExtractGoldBean.class);
            entity.setAddTimeString(UF.getFormatDateTime(extractGold.getAddTime()));
            return entity;
        }
        return null;
    }

    @Transactional
    @Override
    public void applyExtractGold(ApplyExtractGoldBean applyExtractGoldBean) {
        LoginBean loginBean = LoginHelper.getLoginBean();
        Ensure.that(loginBean == null).isTrue("00000102");
        // 1、获取分布式锁防止重复调用 =====================================================
        String orderSubmitKey = PayDistributePrefix.PAY_APPLY_EXTRACT_GOLD + loginBean.getId();
        // 2、获取分布式锁进行对账户锁定 =====================================================
        if(redisGlobalLock.lock(orderSubmitKey, CommonConstants.PAY_ORDER_SUBMIT_LOCK_TIME, TimeUnit.MILLISECONDS)) {

            Ensure.that(applyExtractGoldBean.getName()).isNull("17002001"); //姓名不能为空
            Ensure.that(applyExtractGoldBean.getMobile()).isNull("17002002"); //手机号码不能为空
            Ensure.that(applyExtractGoldBean.getIdCard()).isNull("17002003"); //身份证号码不能为空
            Ensure.that(applyExtractGoldBean.getAmount()).isNull("17002004"); //提金克数不能为空

            Ensure.that(Common.validateMobile(applyExtractGoldBean.getMobile())).isFalse("17002009");   //手机号码不正确
            Ensure.that(new IdcardValidator().isIdcard(applyExtractGoldBean.getIdCard())).isFalse("17002011");   //身份证不合法

            Ensure.that(Common.isNumeric(applyExtractGoldBean.getAmount()+"")).isFalse("17002006"); //验证提金克数是否是数字--本次不做正整数验证
            BigDecimal bd = new BigDecimal(10);  //提金克数是10的整数倍
            BigDecimal result  = applyExtractGoldBean.getAmount().divideAndRemainder(bd)[1];  //取余  0:是取商 1:是取余
            Ensure.that(result.compareTo(BigDecimal.valueOf(0)) == 0).isFalse("17002008"); //提金克数是10克的整数倍

            Ensure.that(Common.isNumeric(applyExtractGoldBean.getPayPassword()+"")).isFalse("17000407"); //验证交易密码是否是数字
            Ensure.that(applyExtractGoldBean.getPayPassword().length() == 6).isFalse("17000408");  //验证交易密码长度是否正确

            //验证交易密码是否正确
            // 交易密码验证
            SerializeObject obj = memberUserService.validatePayPassword(loginBean.getId(), applyExtractGoldBean.getPayPassword());
            Ensure.that(null == obj || obj.getCode() != ResultType.NORMAL).isTrue("17000409");

            MemberGoldBean memberGoldBean = memberGoldService.findByMemberId(loginBean.getId());

            //验证资产
           /* Ensure.that(applyExtractGoldBean.getAmount().compareTo(memberGoldBean.getUsableAmount()) > 0).isTrue("17002010");   //可用提金克数不足*/

            //扣除资产--传递金变成负数
            //memberGoldService.addPrincipalNowAmount(loginBean.getId(), applyExtractGoldBean.getAmount().multiply(BigDecimal.valueOf(-1l)), BillGoldTradeType.EXTRACT_GOLD, null);
            //memberGoldService.addPrincipalNowAmount(loginBean.getId(), BigDecimal.valueOf(10l), BillGoldTradeType.EXTRACT_GOLD, null);
            //获取当前金价
            SerializeObject serializeObject = priceService.currentGoldPrice();
            if(null == serializeObject || serializeObject.getCode() != ResultType.NORMAL) {
                Ensure.that(true).isTrue("17000708");
            }
            BigDecimal currentGoldPrice = new BigDecimal(serializeObject.getData().toString());
            BigDecimal[] payAmount = memberGoldService.payAmount(loginBean.getId(), applyExtractGoldBean.getAmount(), BillGoldTradeType.EXTRACT_GOLD, currentGoldPrice, BigDecimal.ZERO);
            Ensure.that(null == payAmount).isTrue("17000707");

            //生成记录
            //生成商户流水号
            String orderId = SerialNumberWorker.getInstance().nextId();
            ExtractGold extractGold = dozerBeanMapper.map(applyExtractGoldBean, ExtractGold.class);
            extractGold.setId(UF.getRandomUUID());
            extractGold.setOrderId(orderId);
            extractGold.setMemberId(loginBean.getId());
            extractGoldMapper.insert(extractGold);
        }else{
            // 如果没有获取锁
            logger.info("-------没有获取到锁-------");
            Ensure.that(true).isTrue("17000706");
        }
    }

    @Override
    public List<ExtractGoldBean> findExportList(ExtractGoldParamBean extractGoldParamBean) {
        List<ExtractGoldBean> list = extractGoldMapper.findList(extractGoldParamBean);
        return list;
    }

    public static void main(String[] args) {
       /* System.out.println(5%5);
        BigDecimal对象取余运算 [0] 是商 [1] 是余
        BigDecimal dt1 = BigDecimal.valueOf (6);
        BigDecimal dt2 = BigDecimal.valueOf (5);
        BigDecimal str = dt1.divideAndRemainder(dt2)[1];*/
       /* BigDecimal dt1 = new BigDecimal("5");
        System.out.println(dt1.);*/
    }
}
